package cn.yiya.shiji.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;

import com.networkbench.agent.impl.NBSAppAgent;
import com.networkbench.com.google.gson.Gson;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import cn.yiya.shiji.R;
import cn.yiya.shiji.business.ApiRequest;
import cn.yiya.shiji.business.HttpMessage;
import cn.yiya.shiji.business.MsgCallBack;
import cn.yiya.shiji.business.RetrofitRequest;
import cn.yiya.shiji.config.BaseApplication;
import cn.yiya.shiji.config.Configration;
import cn.yiya.shiji.config.CustomEvent;
import cn.yiya.shiji.config.HttpOptions;
import cn.yiya.shiji.entity.DeviceInfo;
import cn.yiya.shiji.entity.HtmlInfo;
import cn.yiya.shiji.entity.SystemSkinObject;
import cn.yiya.shiji.utils.FileUtil;
import cn.yiya.shiji.utils.SharedPreUtil;
import cn.yiya.shiji.utils.SimpleUtils;
import cn.yiya.shiji.utils.Util;

public class SplashActivity extends Activity {

    long startTime;
    long endTime;
    WebView startWebView;
    String mainActivityDest = "";
    String flashId;
    SharedPreferences sharedPreferences;
    String skinTime;
    public Bitmap bitmap;

    float density;


    public final static String SKIN_PATH = Environment.getExternalStorageDirectory() + "/shiji/appSkin/";     //  获得SD卡的路径
    private ImageView ivBackground;
    private Handler mHandler;
    private Runnable runnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);
        startTime = System.currentTimeMillis();
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                initSuccess();
                return false;
            }
        });

        initViews();
        init();

        Intent intent = getIntent();
        if (intent != null) {
            mainActivityDest = intent.getStringExtra("main_activity_dest");
            flashId = intent.getStringExtra("flashId");
        }
    }

    private void initViews() {
        startWebView = (WebView) findViewById(R.id.startwebview);
        ivBackground = (ImageView) findViewById(R.id.startimage);
        ivBackground.setImageResource(R.drawable.appstart);
        //  替换启动图片
//        if ((BitmapFactory.decodeFile((ALBUM_PATH + "app_start.jpg"))) != null) {
//            startimage.setImageBitmap(BitmapFactory.decodeFile((ALBUM_PATH + "app_start.jpg")));
//        } else {
//            startimage.setImageResource(R.drawable.startpage);
//        }

        getDeviceInfo();
        BaseApplication.getInstance().getAppStartImage();    // 获取网络启动图片
//        getSkin();
        startWebView.loadUrl("file:///android_asset/start/index.html");

        goToNextActivity();

        startWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100)
                    ivBackground.setVisibility(View.GONE);
            }
        });
    }

    private void init() {
        // 听云监听
        if (HttpOptions.ShowTYPoint) {
            NBSAppAgent.setLicenseKey(Configration.TingYunKey).start(this);
        }

        //友盟统计入口
        MobclickAgent.updateOnlineConfig(this);
        CustomEvent.onEvent(SplashActivity.this, ((BaseApplication) getApplication()).getDefaultTracker(), "SplashActivity", CustomEvent.Splash);
        AnalyticsConfig.enableEncrypt(true);

        BaseApplication.isInit = true;
        DisplayMetrics metric = getResources().getDisplayMetrics();
        density = metric.densityDpi;
    }

    // 当前是否新版本
    private boolean checkVersion() {
        String curVersion = "";
        PackageManager manager = getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            curVersion = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        String sharedVersion = SharedPreUtil.getString(getApplicationContext(),
                SharedPreUtil.DM_APP_DB,
                SharedPreUtil.newAppVersion);

        if (TextUtils.isEmpty(sharedVersion) || !sharedVersion.equals(curVersion)) {
            SharedPreUtil.putString(getApplicationContext(), // 提示一次就把newAppVersion的值修改掉
                    SharedPreUtil.DM_APP_DB,
                    SharedPreUtil.newAppVersion,
                    curVersion);
            return true;
        }

        return false;
    }

    // 获取设备详细信息并上传到服务器
    private void getDeviceInfo() {
        DeviceInfo info = new DeviceInfo();
        info.setChannel(Util.getChannelName(this));
        info.setCode(Util.getCurVersion(this));
        info.setPhone(Util.getPhoneInfo(this));
        info.setNetwork(Util.GetNetworkType(this));
        info.setIdfa(Util.getUUID(this));
        String code = SharedPreUtil.getString(this, "shiji", "htmlCode");
        info.setOs("Android_" + android.os.Build.VERSION.SDK_INT);
        info.setVersion(Util.getCurVersionName(this) + "(" + code + ")");
        String json = new Gson().toJson(info);
        String str64 = android.util.Base64.encodeToString(json.getBytes(), Base64.NO_WRAP);
        SharedPreUtil.putString(this, "shiji", "device", str64);
    }

    private void getSkin() {
        new RetrofitRequest<SystemSkinObject>(ApiRequest.getApiShiji().getSkin()).handRequest(
                new MsgCallBack() {
                    @Override
                    public void onResult(HttpMessage msg) {
                        if (msg.isSuccess()) {
                            sharedPreferences = getSharedPreferences("skin", 0);
                            skinTime = sharedPreferences.getString("skintime", "0");
                            final SystemSkinObject object = (SystemSkinObject) msg.obj;

                            if (object == null || object.list == null || object.list.size() == 0) {
                                goToNextActivity();
                                return;
                            }

                            // 判断数据存在
                            if (object.empty || object.timestamp == null) {
                                File skinFile = new File(SKIN_PATH);
                                FileUtil.deleteFile(skinFile);
                                goToNextActivity();
                                return;
                            }

                            // 判断时间的顺序性,如果时间相等并且文件存在，则不必去下载
                            if (Long.parseLong(object.timestamp) <= Long.parseLong(skinTime) && bFile()) {
                                goToNextActivity();
                                return;
                            }

                            sharedPreferences.edit().putString("skintime", "" + object.timestamp).commit();
                            sharedPreferences.edit().putString("begintime", "" + object.begin_time).commit();
                            sharedPreferences.edit().putString("endtime", "" + object.end_time).commit();
                            getDownSkinImage(object.list);

                        } else {
                            goToNextActivity();
                        }
                    }
                }
        );
    }

    private void getDownSkinImage(final ArrayList<HtmlInfo> list) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < list.size(); i++) {
                        URL downUrl;
                        if (!TextUtils.isEmpty(list.get(i).getUrl())) {
                            if (i == 0) {
                                String url = list.get(i).getUrl();
                                downUrl = new URL(url);
                                InputStream is = downUrl.openStream();
                                bitmap = BitmapFactory.decodeStream(is);
                                is.close();
                            } else if (density >= 320) {
                                int width = Util.getImgInfo(SplashActivity.this, R.drawable.icon_mall_selector)[1];
                                String url = Util.transferImage(list.get(i).getUrl(), SimpleUtils.dp2px(SplashActivity.this, width));
                                downUrl = new URL(url);
                                InputStream is = downUrl.openStream();
                                bitmap = BitmapFactory.decodeStream(is);
                                is.close();
                            } else {
                                String url = Util.transferImage(list.get(i).getUrl(), SimpleUtils.dp2px(SplashActivity.this, 42));
                                downUrl = new URL(url);
                                InputStream is = downUrl.openStream();
                                bitmap = BitmapFactory.decodeStream(is);
                                is.close();
                            }
                            saveFile(SKIN_PATH, bitmap, list.get(i).getType() + ".png");
                            goToNextActivity();
                        }
                    }
                } catch (Exception e) {
                    goToNextActivity();
                }
            }
        }).start();
    }

    public void saveFile(String path, Bitmap bm, String fileName) throws IOException {
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName);

        if (!myCaptureFile.exists()) {
            myCaptureFile.createNewFile();
        }

        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(myCaptureFile));

        if (!myCaptureFile.exists()) {
            myCaptureFile.createNewFile();
        }

        bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
        bos.flush();
        bos.close();
    }

    private boolean bFile() {
        File path1 = new File(SKIN_PATH);
        return path1.exists();
    }

    private void goToNextActivity() {
        runnable = new Runnable() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(0);
            }
        };
        endTime = System.currentTimeMillis();
        long animTime = startTime + 5000;
        if (animTime > endTime) {
            mHandler.postDelayed(runnable, animTime - endTime);
        } else {
            initSuccess();
        }
    }

    private void initSuccess() {
        mHandler.removeCallbacks(runnable);
        if (checkVersion()) {
            startActivity(new Intent(SplashActivity.this, GuideActivity.class));
            finish();
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        } else {
            //判断是否有main_activity_dest flash
            if (!TextUtils.isEmpty(mainActivityDest) && mainActivityDest.equals("flash")) {
                mainActivityDest = "";
                Intent intent = new Intent(getApplicationContext(), ADActivity.class);
                intent.putExtra("main_activity_dest", "flash");
                intent.putExtra("flashId", flashId);
                startActivity(intent);
            } else {
                startActivity(new Intent(SplashActivity.this, ADActivity.class));
            }

            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        startWebView.stopLoading();
        startWebView.removeAllViews();
        startWebView.destroy();
    }
}
